package top.marken.onlineclass.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.marken.onlineclass.model.entity.VideoOrder;
import top.marken.onlineclass.model.request.VideoOrderRequest;
import top.marken.onlineclass.service.VideoOrderService;
import top.marken.onlineclass.util.JsonData;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 录像订单接口
 */
@RestController
@RequestMapping("/api/v1/pri/order")
public class VideoOrderController {
    @Autowired
    private VideoOrderService videoOrderService;

    /**
     * 购买录像
     * @param orderRequest 录像信息
     * @param request 请求信息
     * @return
     */
    @PostMapping("/save")
    public JsonData save(@RequestBody(required = true) VideoOrderRequest orderRequest, HttpServletRequest request) {
        Integer userId = (Integer) request.getAttribute("user_id");
        if (userId == null) {
            return JsonData.buildFail(null,"用户未登录，请先登录！");
        }

        int code = videoOrderService.save(orderRequest.getVideoId(),userId,orderRequest.getState());
        switch (code) {
            case VideoOrderService.SAVE_CODE_ALREADY_EXIST:
                return JsonData.buildFail(null,"您已经购买过此课程！");
            case VideoOrderService.SAVE_CODE_ERROR:
                return JsonData.buildError(null,"购买课程时出现错误！");
            case VideoOrderService.SAVE_CODE_FAIL:
                return JsonData.buildFail(null,"购买课程失败！");
            case VideoOrderService.SAVE_CODE_SUCCESS:
                return JsonData.buildSuccess(null,"购买课程成功！");
            default:
                return JsonData.buildError(null,"未知错误！");
        }
    }

    /**
     * 已购买的订单列表接口
     * @param request
     * @return
     */
    @GetMapping("/list")
    public JsonData list(HttpServletRequest request) {
        Integer userId = (Integer) request.getAttribute("user_id");
        List<VideoOrder> videoOrders = videoOrderService.listVideoOrderByUserId(userId, VideoOrder.STATE_PAID);
        return JsonData.buildSuccess(videoOrders);
    }
}
